package helpers;

import utilisateurs.modeles.Film;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import servlets.LoadServlet;

public class YouTubeHelper {
    
    private YouTubeHelper() {
    }

    public static void getXML(LoadServlet servlet) {
        File directory = new File(servlet.getServletContext().getRealPath("xml"), "youtube");

        // création du dossier youtube s'il n'existe pas
        if (!directory.exists() || !directory.isDirectory()) {
            directory.mkdir();
        }

        if (directory.exists() && directory.isDirectory()) {
            try {
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Collection<Film> videoGames = servlet.getVideoGameFacade().getAll();

                for (Film videoGame : videoGames) {
                    try {
                        File file = new File(directory, videoGame.getTitle().replaceAll("[\\W]", "") + ".xml");

                        if (file.length() == 0) {
                            file.delete();
                        }
                        
                        if (file.createNewFile()) {
                            String params = URLEncoder.encode("official trailer " + videoGame.getTitle(), "UTF-8");
                            URL url = new URL("http://gdata.youtube.com/feeds/api/videos?q=" + params);
                            ReadableByteChannel rbc = Channels.newChannel(url.openStream());
                            FileOutputStream fos = new FileOutputStream(file);
                            fos.getChannel().transferFrom(rbc, 0, 1 << 24);
                            System.out.println("#### " + file.getAbsolutePath() + " ####");
                        }
                        
                        String youTubeID = parseXML(builder, file);
                        videoGame.setIdYouTubeVideo(youTubeID);
                        servlet.getVideoGameFacade().edit(videoGame);
                        System.out.println("#### " + file.getName() + " #### " + videoGame.getTitle() + " #### " + videoGame.getCategorie().getName() + " #### " + youTubeID + " ####");
                    } catch (SAXException ex) {
                        Logger.getLogger(YouTubeHelper.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(AmazonHelper.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(YouTubeHelper.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private static String parseXML(DocumentBuilder builder, File file) throws SAXException, IOException {
        Document document = builder.parse(file);
        NodeList entries = document.getElementsByTagName("id");

        if (entries.getLength() > 1) {
            Node entry = entries.item(1);
            String videoURL = entry.getTextContent();
            String[] videoArray = videoURL.split("/");
            return videoArray[videoArray.length - 1];
        }

        return null;
    }
}
